package android.javaClasses;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

/**
 * Created by IntelliJ IDEA.
 * User: michelle
 * Date: 4/18/11
 * Time: 11:14 AM
 * To change this template use File | Settings | File Templates.
 */


public class Server {
    private final int PORT = 12345;
    private Receiver receiver;
    private Stream serverStream;
    private Handler mHandler;


    public Server(Handler mHandler) {
        this.mHandler = mHandler;
        receiver = new Receiver(PORT, new Receiver.OnNewSocketStreamListener() {
            @Override
            public void onNewSocket(Stream stream) {
                serverStream = stream;
                stream.setOnCloseStreamListener(new Stream.OnCloseStreamListener() {
                    @Override
                    public void onCloseStream() {
                        //Stream is closed automatically, don't need to call close()
                        //Do something
                    }
                });
                stream.setOnReadObjectListener(new Stream.OnReadObjectListener() {
                    @Override
                    public void onReadObject(Content content) {
                        actOnObject(content);
                    }
                });
                stream.startReading();
            }
        });

    }

    public void startServer() {
      receiver.start();
    }

    public void stopServer() {
      receiver.stop();
    }

    //Writes an object of type Content to the stream
    public void writeToStream(Content content) {
        serverStream.writeObject(content);
    }

    //Sends data to UI-thread (main) for it to be updated there
    private void sendToMain(Content content) {
        Message msg = Message.obtain();
        msg.what = 1;
        String res = content.getText();
        Bundle b = new Bundle();
        b.putString("message", res);
        msg.setData(b);
        mHandler.sendMessage(msg);

    }

    private void actOnObject(Content content) {
        Message msg = Message.obtain();
        Bundle bundle = new Bundle();
        int id = content.getTypeOfContent();
        switch (id) {
            case Content.SEND_USERNAME:
                String playerName = content.getPlayerName();
                msg.what = Content.SEND_USERNAME;
                bundle.putString("playerName", playerName);
                msg.setData(bundle);
                mHandler.sendMessage(msg);
                break;
            case Content.SEND_CHOSEN_CELL:
                msg.what = Content.SEND_CHOSEN_CELL;
                float yValue = content.getyValue();
                float xValue = content.getxValue();
                bundle.putFloat("xValue", xValue);
                bundle.putFloat("yValue", yValue);
                msg.setData(bundle);
                mHandler.sendMessage(msg);
                break;
        }
    }

}